<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="content">{{toName}}</block>
		</cu-custom>
		<scroll-view class="cu-chat" scroll-y="true" :scroll-with-animation="true" :scroll-top="scrollTop" id="scrollview"
		 :style="'height: calc(100vh - 50px - '+toHeight+'px)'">
			<view class="in-item" v-for="(item,index) in msglist" :key="index">
				<!-- 自己发送的信息 -->
				<view class="cu-item self" v-if="item.isfrom == 1">
					<view class="main" v-if="item.type == 'text'">
						<view class="content bg-green shadow" v-html="item.msg">
						</view>
					</view>
					<view class="main" v-if="item.type == 'sayImage'">
						<image :src="item.msg" class="radius" mode="widthFix"></image>
					</view>
					<view class="cu-avatar radius" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);"></view>
					<view class="date">{{item.time}}</view>
				</view>

				<!-- 好友发送的信息 -->
				<view class="cu-item" v-else>
					<view class="cu-avatar radius" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);"></view>
					<view class="main" v-if="item.type == 'text'">
						<view class="content bg-green shadow">
							<rich-text :nodes="item.msg"></rich-text>
						</view>
					</view>
					<view class="main" v-if="item.type == 'sayImage'">
						<image :src="item.msg" class="radius" mode="widthFix"></image>
					</view>
					<view class="date">{{item.time}}</view>
				</view>
			</view>
		</scroll-view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action" @click="showEmoji">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<input class="solid-bottom" v-model="sendContent" :adjust-position="false" :focus="false" maxlength="300"
			 cursor-spacing="10"></input>
			<view class="action" @click="sendImg">
				<text class="cuIcon-add text-grey"></text>
			</view>
			<button class="cu-btn bg-green shadow" @click="sendMsg">发送</button>
		</view>
		<!-- 表情 -->
		<scroll-view scroll-y="auto" class="emoji" v-if="emojiShow">
			<block v-for="(item,index) in emotions" :key="index">
				<image :src="item[1]" mode="aspectFill" :data-text='item[0]' @click="expression"></image>
			</block>
		</scroll-view>

	</view>
</template>

<script>
	import Request from '../../lib/request.js'
	import Util from '../../lib/util.js'
	import Config from '../../lib/config.js'
	import emoji from '../../lib/emoji.js'

	export default {
		data() {
			return {
				toHeight:this.CustomBar,
				scrollTop: 0,
				InputBottom: 0,
				fromid: 0,
				toid: 0,
				ws: null,
				fromHeadImg: null, // 我的头像
				toHeadImg: null, // 好友头像
				toName: null, // 好友名称
				online: null, // 是否在线
				msglist: [], // 消息列表
				sendContent: "", // 发送消息内容
				oldbottom: 0,
				emotions:emoji.emotions, // 表情
				emojiShow:false
			};
		},
		onLoad: function(options) {
			this.fromid = options.fromid
			this.toid = options.toid
		},
		created() {
			this.initConn();
		},
		methods: {
			//初始化websocket
			initConn() {
				let ws = this.ws = new WebSocket("ws://127.0.0.1:8282") //创建WebSocket实例
				this.ws.onopen = this.onOpen
				this.ws.onmessage = this.onMessage
				// 初始化完成，标记所有消息已读
				this.signRead()
			},
			onOpen(e) {
				// websocket连接成功 初始化
				// 初始化发送消息 绑定用户唯一标识uid
				let bild = '{"type":"bind","fromid":"' + this.fromid + '"}'
				this.ws.send(bild)
				// 初始化用户头像
				this.get_head(this.fromid, this.toid)
				// 初始化好友昵称
				this.get_name(this.toid)
				// 初始化聊天消息数默认10条
				this.message_load()

				// 初始化对方是否在线
				let isOnline = '{"type":"online","fromid":"' + this.fromid + '","toid":"' + this.toid + '"}'
				this.ws.send(isOnline)
			},
			onMessage(e) {
				let that = this
				let message = eval("(" + e.data + ")")

				switch (message.type) {
					case "text": // 文本消息
						if (this.toid == message.fromid) { // 只接收当前聊天对象的消息
							message.isfrom = 2 // 1等于自己发送的消息 2等于好友发送的消息
							message.msg = message.data
							message.time = Util.getLocalTime(message.time)
							let msg = Util.showC2C(message)
							that.msglist = that.msglist.concat(msg)
						}
						setTimeout(() => {
							that.goScrollTop()
						}, 100)
						break;
					case "save": // 将接收到的消息保存到数据库
						that.saveMessage(message);
						// 发送消息时判断是否在线
						if (message.isread === 1) { // 在线
							that.online = 1
						} else { // 离线
							that.online = 0
						}
						break;
					case "sayImage": // 图片消息
						if (toid == message.fromid) { // 只接收当前聊天对象的消息
							message.isfrom = 2
							message.msg = message.img_name
							message.time = Util.getLocalTime(message.time)
							that.msglist = that.msglist.concat(message)
						}
						setTimeout(() => {
							that.goScrollTop()
						}, 100)
						break;
					case "online": // 登录状态
						if (message.status === 1) { // 好友在线
							that.online = 1
						} else { // 离线
							that.online = 0
						}
				}
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			//页面滚动到最底部
			goScrollTop() {
				let that = this
				let query = uni.createSelectorQuery();
				query.selectAll('.in-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();
				query.exec((res) => {
					let Height = 0;
					res[0].forEach((rect) => {
						Height += rect.height + 100
					})
					that.scrollTop = Height
				})
			},
			// 获取对话页面双方头像
			get_head(fromid, toid) {
				let that = this;
				Request.httpTokenRequest({
					url: 'Chat/getHeadImg',
					method: 'POST'
				}, {
					fromid: this.fromid,
					toid: this.toid
				}).then(res => {
					if (res.code == 1) {
						// 请求成功返回数据
						that.fromHeadImg = res.data.fromImg;
						that.toHeadImg = res.data.toImg;
					} else {
						uni.showModal({
							content: res.msg,
							showCancel: false
						})
					}
				})
			},
			// 获取聊天对象昵称
			get_name(toid) {
				let that = this;
				Request.httpTokenRequest({
					url: 'Chat/getNickName',
					method: 'POST'
				}, {
					toid: this.toid
				}).then(res => {
					if (res.code == 1) {
						// 请求成功返回数据
						that.toName = res.data.nickname;
					} else {
						uni.showToast({
							title: res.msg
						})
					}
				})
			},
			// 初始化对话消息
			message_load() {
				let that = this;
				Request.httpTokenRequest({
					url: 'Chat/messageLoad',
					method: 'POST'
				}, {
					fromid: this.fromid,
					toid: this.toid
				}).then(res => {
					if (res.code == 1) {
						// 请求成功返回数据
						for (let i = res.data.length - 1; i >= 0; i--) {
							switch (res.data[i].type) {
								case 1: // 文本
									res.data[i].type = 'text'
									res.data[i].msg = res.data[i].content
									res.data[i].time = Util.getLocalTime(res.data[i].time)
									if (res.data[i].fromid == this.fromid) {
										res.data[i].isfrom = 1
									} else {
										res.data[i].isfrom = 2
									}
									res.data[i] = Util.showC2C(res.data[i])
									console.log(res.data[i])
									that.msglist = this.msglist.concat(res.data[i])
									break
								case 2: // 图片
									res.data[i].type = 'sayImage'
									res.data[i].msg = res.data[i].content
									res.data[i].time = Util.getLocalTime(res.data[i].time)
									if (res.data[i].fromid == this.fromid) {
										res.data[i].isfrom = 1
									} else {
										res.data[i].isfrom = 2
									}
									that.msglist = this.msglist.concat(res.data[i])
									break
							}
						}
						// 因为数据处理完成后，页面渲染也需要时间。获取子元素的高度进行自动滚动到底部
						// 如果不加延时的话则子元素还没被渲染。获取的高度是0则不会自动滚动到底部
						setTimeout(() => {
							that.goScrollTop()
						}, 100)
					} else {
						uni.showToast({
							title: res.msg
						})
					}
				})
			},
			// 保持长连接请求
			saveMessage(message) {
				Request.httpTokenRequest({
					url: 'Chat/saveMessage',
					method: 'POST'
				}, message).then(res => {
					if (res.code != 1) {
						uni.showToast({
							title: res.msg
						})
					}
				})
			},
			// 点击发送消息
			sendMsg() {
				if (this.sendContent == "") {
					uni.showToast({
						title: "发送消息不能为空",
					})
					return
				}
				let message = '{"data":"' + this.sendContent + '","type":"say","fromid":"' + this.fromid + '","toid":"' + this.toid +
					'"}';
				this.ws.send(message);
				let arr = {
					isfrom: 1,
					type: 'text',
					msg: this.sendContent,
					time: Util.getLocalTime(new Date().getTime() / 1000)
				}
				let msg = Util.showC2C(arr)
				this.msglist = this.msglist.concat(msg)
				this.sendContent = ""
				setTimeout(() => {
					this.goScrollTop()
				}, 100)
			},

			// 点击发送图片
			sendImg() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						let data = {
							'fromid': that.fromid,
							'toid': that.toid,
							'online': that.online
						}
						uni.uploadFile({
							url: Config.baseUrl + 'Chat/uploadImg',
							method: 'POST',
							filePath: res.tempFilePaths[0],
							name: 'image',
							formData: data,
							success(e) {
								let res = JSON.parse(e.data)
								if (res.code == 1) {
									// 上传成功，视图窗口增加一条消息
									let arr = {
										isfrom: 1,
										type: 'sayImage',
										msg: res.data['img_name'],
										time: Util.getLocalTime(new Date().getTime() / 1000)
									}
									that.msglist = that.msglist.concat(arr)
									setTimeout(() => {
										that.goScrollTop()
									}, 100)
									// 图片上传成功 给服务端发送消息
									let message = '{"data":"' + res.data['img_name'] + '","type":"sayImage","fromid":"' + that.fromid + '","toid":"' +
										that.toid + '"}'
									that.ws.send(message)
								} else {
									uni.showModal({
										content: res.msg,
										showCancel: false
									})
								}
							}
						})
					}
				});
			},
			// 标记所有消息数据已读
			signRead(){
				Request.httpTokenRequest({url: 'Chat/isRead',method: 'POST'},{'fromid':this.fromid,'toid':this.toid}).then(res=>{
					console.log(res)
				})
			},
			// 表情展示
			showEmoji(){
				if(this.emojiShow){
					this.emojiShow = false
					this.toHeight = this.CustomBar
				}else{
					this.emojiShow = true
					this.toHeight = this.CustomBar + 120
				}
			},
			//选中表情
			expression(e) {
				let emoji = e.currentTarget.dataset.text
				//拼接表情再消息后面
				this.sendContent += emoji
			},
		}
	}
</script>

<style lang="less">
	.emoji{
		position: fixed;
		z-index: 1024;
		width: 100%;
		height: 120px;
		background: #FFF;
		bottom: 50px;
		image{
			width: 30px;
			height: 30px; 
			margin-left: 10px;
		}
	}
</style>
